#!/usr/bin/perl

# Do simulation results file globbing
$outputdir = "/home/rumen/simulation1";
$analysisdir = "/home/rumen/cryptsim/analysis";
#$query = "K=.*RSM=3"; # .* means match any character (.) any number of times (*) in grep regex
$query = $ARGV[0]; # .* means match any character (.) any number of times (*) in grep regex
# CONSTANTS for statistical analysis
$DELTA = 0.01; # If at some point in time, divergence drops 1% or lower, call that a trough, or homogenizat

if (!(-d $outputdir)) {
    mkdir($outputdir, 0777);
}
chdir($outputdir);
$args = "rm -fr $outputdir/postjob*";
system($args);

# Get all sweeps that match the query
opendir(DIR, $outputdir);
@files = grep { /$query/ } readdir(DIR);
closedir(DIR);
$sweepcnt=0;
foreach $f (@files) {
    print STDERR "Processing $f\n";
    $dir = $outputdir."/".$f;
    opendir(DIR, $dir);    
    @clonesfiles = grep { /clones$/ } readdir(DIR);
    rewinddir(DIR);
    @patternsfiles = grep { /patterns$/ } readdir(DIR);
    closedir(DIR);

    # go to the folder of that sweep
    chdir($dir);
    foreach $cf (@clonesfiles) {
	foreach $pf (@patternsfiles){
	    @r1 = split (/\./, $cf);
	    @r2 = split (/\./, $pf);
	    # Only when we have output for clones and patterns of a particular replicate
	    if($r1[0] eq $r2[0]){
		# Prepare postprocessing job for that replicate
		$sweepcnt++;
		open(out2, ">$outputdir/postjob$sweepcnt.sh");
		print out2 "#!/bin/bash\n";		
		print out2 "perl $analysisdir/postprocessing.of.simulation.run.pl $dir $dir/$cf $dir/$pf\n";
		print out2 "perl $analysisdir/postprocessing.of.simulation.run.calculate.divergence.over.time.pl $dir/".$r1[0]."\n";
		print out2 "R CMD BATCH --vanilla --slave  '--args runfolder=\"$dir\" run=\"".$r1[0]."\" delta=$DELTA' $analysisdir/postprocessing.of.parameter.sweeps.calculate.divergence.statistics.R\n";	
		close(out2);		
	    }
	}
    }
}


open(out,">$outputdir/submit.post.jobs.pl");
print out q(#!/usr/bin/perl

	    if(defined($ARGV[1])){
		for($i=$ARGV[0]; $i<=$ARGV[1]; $i++){
		    $args = "qsub -l h_stack=8192K -q all.q -p -100 -cwd postjob$i.sh";
		    system($args);    
		}
	    } else {
		$args = "qsub -l h_stack=8192K -q all.q -p -100 -cwd postjob".$ARGV[0].".sh";
		system($args);    
	    }
);
close out;

